<template>
	<view>
		<cu-custom  bgColor="bg-black-two"  :isBack="true">
			<block slot="content">余额中心</block>
		</cu-custom>
		
		<view class="my-bg">
			<view class="flex justify-center" style="padding-top: 10px;">
				<text style="font-size: 20px;color: #fff;">{{yue}}</text>
			</view>
			<view class="flex justify-center">
				<text style="font-size: 10px;margin-bottom: 10px;">余额(元)</text>
			</view>
			<view class="flex justify-between" style="padding: 10px 50px;">
				<button @click="showModal('tabModel')" class="cu-btn bg-grey loginout-btn" style="width: 40%;">
					充值
				</button>
				<button @click="showModal('tuikuanModel')" class="cu-btn bg-grey loginout-btn" style="width: 40%;background-color: #2196F3;">
					退款
				</button>
			</view>
		</view>
		
		<view class="my-bg">
			<view class="flex justify-between my-title-bg" style="font-weight: bold;color: white;">
				<view>余额变动明细</view>
			</view>
			<view v-for="(item,index) in detailList" :key="index"
			:class="index == Number(detailList.length-1) ? 'my-title-bg-last':'my-title-bg'">
				<view class="flex justify-between ">
					<view>{{item.desc}}</view>
					<view>{{item.number}}</view>
				</view>
				<view class="flex justify-between" style="color: #6A6A71;">
					<view>{{item.create_time}}</view>
				</view>
			</view>	
		</view>
		
		
		<!-- 模态框：点击充值按钮显示个人充值、企业支付 -->
		<view class="cu-modal" :class="modalName=='tabModel'?'show':''" :style="isTypeChonezhi">
			<view class="cu-dialog" style="background-color:#FFF;height:310px;">
				<view style="width:90%;margin:0 auto;">
					<view class="flex">
						<scroll-view scroll-x class="bg-white nav text-center">
							<view class="cu-item" :class="index==TabCur?'text-blue cur':''" 
								v-for="(item,index) in tabList" :key="index" @tap="tabSelect" :data-id="index">
								{{item}}
							</view>
						</scroll-view>	
						<view class="action" @tap="hideModal" style="padding-top: 10px;">
							<text class="cuIcon-close" style="color: #847d7d;"></text>
						</view>
					</view>
					
					<!-- TabCur：0 个人支付 -->
					<view v-if="!TabCur" style="padding-top: 15px;">
						<view class="open-block" style="padding-bottom: 10px;text-align: left;color: #100f0f;">
							<view style="margin-top:20px;padding: 20px 45px;">
								<view>
									<view style="padding-bottom: 5px;">
										请输入充值金额（元）
									</view>
									<view>
										<input class="uni-input"
										v-model='chongzhiNumber' style="color:#00A99D;font-size:18px;" type="number"></input>
										<view style="height: 1px;background-color: #00A99D;margin:10px auto"></view>
									</view>
								</view>
						</view>
						<view class="flex flex-wrap justify-between align-center" style="width:220px;margin:24px auto;">
							<button @click="hideModal()" class="cu-btn out-btn" style="background-color:#fff;border: 1px solid #00A99D;">取消</button>
							<button @click="checkAuth()" class="cu-btn confirm-btn" style="background-color:#00A99D;width: 45%;">确认充值</button>
						</view>
					</view>
					</view>
					<!-- TabCur：1 企业支付 -->
					<view v-else class="text-black-two" style="margin-top: 15px;">
						<view class="company-pay">收款卡号</view>
						<view class="company-pay text-lg text-bold">1105020209000329330</view>
						<view class="company-pay">收款户名</view>
						<view class="company-pay">常州多博特机器人科技股份有限公司</view>
						<view class="company-pay">开户银行</view>
						<view class="company-pay">中国工商银行股份有限公司常州经济开发区支行</view>
						<view class="company-pay" @click="setCopy()">
							<text class="cuIcon-copy text-green-two" style="font-size: 20px;"></text>
							<text class="text-green-two text-lg">复制</text>
						</view>
					</view>
				</view>
			</view>
		</view>	

		<!-- 退款 -->
		<view class="cu-modal" :class="modalName=='tuikuanModel'?'show':''" :style="isTypeTuikuan">
			<view class="cu-dialog" style="background-color: #FFF;">
				<view class="cu-bar bg-white justify-end">
					<view class="content">退款</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close" style="color: #6A6A71;"></text>
					</view>
				</view>
				<view style="padding:10px 45px 5px 45px;color: #100f0f;text-align: left;">
					<view style="padding-bottom: 15px;">
						<view style="padding-top: 5px;padding-bottom: 5px;">请输入姓名</view>
						<view>
							<input class="uni-input" v-model='name' style="color:#00A99D;font-size:18px;"></input>
							<view style="height: 1px;background-color: #00A99D;"></view>
						</view>
					</view>
					<view style="padding-bottom: 15px;">
						<view style="padding-top: 5px;padding-bottom: 5px;">请输入退款金额（元）</view>
						<view>
							<input class="uni-input" v-model='tuikuanNumber' type="number" style="color:#00A99D;font-size:18px;"></input>
							<view style="height: 1px;background-color: #00A99D;"></view>
						</view>
					</view>
					<view style="padding-bottom: 15px;">
						<view style="padding-top: 5px;padding-bottom: 5px;">请输入银行卡号</view>
						<view>
							<input class="uni-input" v-model='bankCode' type="number" style="color:#00A99D;font-size:18px;"></input>
							<view style="height: 1px;background-color: #00A99D;"></view>
						</view>
					</view>
				</view>
				<view class="flex flex-wrap justify-between align-center" style="width:200px;margin:24px auto;margin-bottom: 40px">
					<button @click="hideModal()" class="cu-btn out-btn" 
								style="background-color:#fff;border: 1px solid #00A99D;">取消</button>
					<button @click="tuikuan()" class="cu-btn confirm-btn" 
							style="background-color:#00A99D;">确认</button>
				</view>
			</view>
		</view>
		
		<!-- 授权提示框 -->
		<view class="cu-modal" :class="tipModalName=='auth'?'show':''" style="z-index: 1111;">
			<view class="cu-dialog bg-white" style="border-radius: 13px;">
				<view class="cu-bar justify-end">
					<view class="content text-black-two">授权提醒</view>
				</view>
				<view class="margin-bottom-sm" style="padding: 15px 0px;">
					<view>
						<text style="font-size: 15px;">
							请授权昵称、头像等公开信息
						</text>
					</view>
					<view class="" style="font-size: 15px;">
						以便为您提供更好的服务
					</view>
				</view>
				<view class="cu-bar padding-bottom-sm" style="justify-content: center;height: 80px;">
					<button  @click="confirmAuth()" class="cu-btn round bg-green-two padding-lr-lg" style="width: 50%;height: 45px;">允许</button>
				</view>
			</view>
		</view>
	
		
	</view>
</template>

<script>
	var _self;
	export default {
		data() {
			return {
				detailList:[],//余额变动明细
				yue:0,//当前余额
				//tab导航栏
				TabCur: 0,
				scrollLeft: 0,
				tabList:['个人支付','企业支付'],
				//模态框
				modalName:'',
				chongzhiNumber:'',//充值金额
				//企业信息
				companyPayList:{
					bankCode:"123456123456789789456",
					bankName:"中国工商银行股份有限公司常州经济开发区支行",
					companyName:"常州多博特机器人科技股份有限公司"
				},
				//退款
				name:'',
				tuikuanNumber:'',//退款金额
				bankCode:'',//银行卡号
				isTypeChonezhi:'',
				isTypeTuikuan:'',
				tipModalName:''
			}
		},
		onShow() {
			_self = this;
			//获取当前余额和积分
			this.getInitData();
		},
		methods: {
			// 获取用户当前余额和积分
			async getInitData(){
				let [err,res] = await this.$http.get('getAccountList',{
					cate : 0
				},{
					token:true,
					checkToken:true ,
				});
				// 失败
				if (!this.$http.errorCheck(err,res)){
					uni.hideLoading();
					return false;
				}
				uni.hideLoading();
				this.detailList = res.data.data.list
				this.yue = res.data.data.userinfo.money
				//更新本地存储的余额
				let userinfo = uni.getStorageSync("userinfo");
				userinfo.money = this.yue;
				uni.setStorageSync("userinfo",userinfo);
			},
			//tab导航栏
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				this.chongzhiNumber = '';
			},
			showModal(name){
				this.modalName=name
				if (name == "tabModel") {
					//打开充值模态框
					this.isTypeTuikuan = "display:none";
					this.isTypeChonezhi = "display:block";
				} else {
					//打开退款模态框
					this.isTypeTuikuan = "display:block";
					this.isTypeChonezhi = "display:none";
				} 
			},
			hideModal() {
				this.modalName = null;
				this.chongzhiNumber = '';
				this.TabCur = 0;
				this.tuikuanNumber = '';
				this.name = '';
				this.bankCode = '';
			},
			//打开授权模态框
			showAuthModal(name){
				this.tipModalName=name;
			},
			hideAuthModal(){
				this.tipModalName = null;
			},
			//验证用户是否授权
			async checkAuth(){
				//判断是否授权，未授权则弹出授权框
				let userId = uni.getStorageSync("userinfo").id;
				uni.showLoading({ title: '加载中...', mask: true });
				// 请求
				let [err,res] = await this.$http.post('getUserSingle',{user_id:userId},{
					token:true,
					checkToken:true ,
				});
				// 请求失败
				if (!this.$http.errorCheck(err,res)){
					uni.hideLoading();
					return false;
				}
				uni.hideLoading();
				if (res.data.data.open_id == "0") {
					//未授权，弹出授权框
					this.showAuthModal('auth');
					console.log('未授权');
					//uni.hideTabBar();//隐藏底部tabBar
				} else {
					this.wxpayAuth();
				}	
			},
			//充值-微信支付
			wxpayAuth(){
				if(Number(this.chongzhiNumber) < 1){
					uni.showToast({
					title:"请输入金额",
					icon:'error'
					})
					return;
				}
				uni.showLoading({
					title:'正在充值..',
					mask:true
				})
				uni.request({
					url: 'https://new.dascloud.cn/front/user/wxlogin',
					method: 'GET',
					data:{
						user_id:uni.getStorageSync("userinfo").id,
						number:this.chongzhiNumber
					},
					header: {  
						'Content-Type': 'application/x-www-form-urlencoded'  
					},
					//sslVerify: false,//本地模拟器调试
					success: pay => {
						uni.hideLoading();
						_self.chongzhiNumber = '';
						console.log(pay);
						uni.requestPayment({
							timeStamp: pay.data.timeStamp,
							nonceStr: pay.data.nonceStr,
							package: pay.data.package,
							signType: pay.data.signType,
							paySign: pay.data.paySign,
							success: function (res) {
								_self.modalName = null;
								uni.showToast({
									title:"充值成功",
									icon:'success'
								})       
								_self.getInitData();
								console.log('success:' + JSON.stringify(res));
							},
							fail: function (err) {
								uni.showToast({
									title:'充值失败',
									icon:'error'
								});
								_self.modalName = null;
								_self.chongzhiNumber = '';
								_self.getInitData();
								console.log('fail:' + JSON.stringify(err));
							}
						});
					}
				})
			},
			//允许授权，获取openid
			confirmAuth(){
				uni.login({
					success:(r)=>{
						console.log(r);
						_self.updateUser(uni.getStorageSync("userinfo").id,r.code);
					},
					fail:(err) => {
						console.log(err);
					}
				});
			},
			async updateUser(userId,code){
				uni.showLoading({ title: '加载中...', mask: true });
				// 请求登录
				let [err,res] = await this.$http.post('updateUserInfo',{
					user_id:userId,
					code:code
					},{
					token:true,
					checkToken:true ,
				});
				// 登录失败
				if (!this.$http.errorCheck(err,res)){
					uni.hideLoading();
					return false;
				}
				uni.hideLoading();
				if (res.data.msg == '授权成功') {
					//授权成功
					uni.showToast({
						title:'授权成功',
						icon:'success'
					});
					this.hideAuthModal();
					//uni.showTabBar();//显示底部tabBar
				} else {
					//授权失败
					uni.showToast({
						title:'授权失败',
						icon:'error'
					});
					this.hideAuthModal();
					//uni.showTabBar();
				}
			},
			setCopy(){
				var strText = "";
				strText += "收款卡号：\n"+this.companyPayList.bankCode+"\n";
				strText += "收款户名：\n"+this.companyPayList.companyName+"\n";
				strText += "开户银行：\n"+this.companyPayList.bankName;
				uni.setClipboardData({
					data: strText, //要被复制的内容
					success: () => { //复制成功的回调函数
						console.log('复制成功');
						console.log(strText);
					}
				});
			},
			//退款
			async tuikuan(){
				if (this.name== null || this.name == '') {
					uni.showToast({
						title:'请输入姓名',
						icon:'error'
					});
				} else if (this.tuikuanNumber== null || this.tuikuanNumber == '') {
					uni.showToast({
						title:'请输入退款金额',
						icon:'error'
					});
				} else if (this.bankCode== null || this.bankCode == '') {
					uni.showToast({
						title:'请输入银行卡号',
						icon:'error'
					});
				} else {
					uni.showLoading({ title: '加载中...', mask: true });
					let paramsArray = {};
					paramsArray.userId = uni.getStorageSync("userinfo").id;
					paramsArray.number = this.tuikuanNumber;
					paramsArray.yinhangka = this.bankCode;
					paramsArray.name = this.name;
					// 请求
					let [err,res] = await this.$http.post('backMoney',paramsArray,{
						token:true,
						checkToken:true ,
					});
					uni.hideLoading();
					if (res.data.msg == "success") {
						uni.showToast({
							title:"提交成功",
							icon:'success'
						})   
						this.modalName = null;
						this.tuikuanNumber = '';
						this.name = '';
						this.bankCode = '';
						this.getInitData();
					} else {
						uni.showToast({
							title:'提交失败',
							icon:'error'
						});
						this.modalName = null;
						this.tuikuanNumber = '';
						this.name = '';
						this.bankCode = '';
						this.getInitData();
					}
				}
			},
		}
	}
</script>

<style>
	.loginout-btn{
		background-color:#22B573;border-radius: 20px;
	}
	.my-title-bg{
		border-bottom: 1px solid #6A6A71;margin: 10px;padding: 0px 5px 5px 5px;
	}
</style>
